package com.xiaoban.filter;

import com.xiaoban.pojo.LoginSyUser;
import com.xiaoban.utils.JwtUtil;
import com.xiaoban.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author 小班哥
 * @version 1.0
 * @date 2024/3/17 11:12
 * @description 拦截器，判断用户token是否合法
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisCache redisCache;

    /**
     *
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取Token
        String token = request.getHeader("token");
        //验证Token是否为空
        if (!StringUtils.hasText(token)){
            //Token为空 放行  这里放行也是也没关系的，因为SpringSecurity还会进行认证
            filterChain.doFilter(request,response);
            return;
        }
        //解析Token
        String UserID;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            UserID = claims.getSubject();
        } catch (Exception e) {
            System.err.println(e.getMessage());
            throw new RuntimeException( "用户身份校验失败！");
        }

        //从Redis中获取用户信息
        LoginSyUser loginSyUser = redisCache.getCacheObject("login:" + UserID);
        //判断用户信息是否为空
        if (Objects.isNull(loginSyUser)){
            throw new RuntimeException("用户未登录");
        }
        //存入SecurityContextHolder
        //TODO 获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginSyUser,null,loginSyUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);
    }
}
